/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   Module Name          : com.yaodian100.ec.image.service.Client
   Module Description   :

   Date Created      : 2010/10/25
   Original Author   : feeling.wang
   Team              : yaodian100
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
   MODIFICATION HISTORY
   ------------------------------------------------------------------------------
   Date Modified       Modified by       Comments
   ------------------------------------------------------------------------------
   ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++*/
package com.yaodian100.ec.image.service;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.FileImageOutputStream;
import javax.imageio.stream.ImageInputStream;

/**
 * @author feeling.wang
 * 
 */
public class ResizeImg {

	static List<File> list = new ArrayList<File>();
	static float compressRatio = 0.9f;
	static int rsWidth = 225;
	static int rsHeight = 225;
	static String path = "d:\\imgtest_new\\";
	static String imgSubName = "_mr225.jpg";

	public static void main(String[] args) throws IOException {
		File f = new File("d:\\imgtest");
		getFile(f);
		// 縮圖
		for (int i = 0; i < list.size(); i++) {
			resizePressAveraging(list.get(i));
		}
	}

	static void resizePressAveraging(File file) throws IOException {
		String prodId = file.getName().substring(0, 8);
		// 因有目錄數限制,所以增加以前商品4碼作分類目錄
		File newFourFolder = new File(path + prodId.substring(0, 4));
		if (!newFourFolder.exists()) {
			newFourFolder.mkdir();
		}
		File newFolder = new File(path + prodId.substring(0, 4) + File.separator + prodId);
		if (!newFolder.exists()) {
			newFolder.mkdir();
		}
		BufferedImage bufferedImage = ImageIO.read(file);
		customChange(bufferedImage, newFolder.getPath() + File.separator + prodId + imgSubName);
	}

	public static void customChange(BufferedImage img, String fileWholePath) {
		BufferedImage bi = img;
		try {
			double ratio = 0.0; // 縮放比例
			Image itemp = img;
			// 計算比例
			double diffH = Integer.valueOf(rsHeight).doubleValue() / Integer.valueOf(bi.getHeight()).doubleValue();
			double diffW = Integer.valueOf(rsWidth).doubleValue() / Integer.valueOf(bi.getWidth()).doubleValue();

			if (diffH < 1 || diffW < 1) {// 只針對比設定尺寸大的做縮圖動作
				if (diffH <= diffW) {
					ratio = Integer.valueOf(rsHeight).doubleValue() / bi.getHeight();
					itemp = bi.getScaledInstance(new Double(img.getWidth() * ratio).intValue(), new Double(img.getHeight()
							* ratio).intValue(), bi.SCALE_AREA_AVERAGING);
				} else if (diffH > diffW) {
					ratio = Integer.valueOf(rsWidth).doubleValue() / bi.getWidth();

					itemp = bi.getScaledInstance(new Double(img.getWidth() * ratio).intValue(), new Double(img.getHeight()
							* ratio).intValue(), bi.SCALE_AREA_AVERAGING);
				}
			}
			BufferedImage image = new BufferedImage(rsWidth, rsHeight, BufferedImage.TYPE_INT_RGB);
			Graphics2D g = image.createGraphics();
			g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
			g.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
			g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
			g.setColor(Color.white);
			g.fillRect(0, 0, rsWidth, rsHeight);
			if (rsWidth == itemp.getWidth(null)) {
				g.drawImage(itemp, 0, (rsHeight - itemp.getHeight(null)) / 2, itemp.getWidth(null), itemp.getHeight(null),
						Color.white, null);
			} else if (rsHeight == itemp.getHeight(null)) {
				g.drawImage(itemp, (rsWidth - itemp.getWidth(null)) / 2, 0, itemp.getWidth(null), itemp.getHeight(null),
						Color.white, null);
			} else {
				g.drawImage(itemp, (rsWidth - itemp.getWidth(null)) / 2, (rsHeight - itemp.getHeight(null)) / 2, itemp
						.getWidth(null), itemp.getHeight(null), Color.white, null);
			}
			g.dispose();
			itemp = image;
			Iterator<ImageWriter> it = ImageIO.getImageWritersBySuffix("jpg");
			if (it.hasNext()) {
				FileImageOutputStream fileImageOutputStream = new FileImageOutputStream(new File(fileWholePath));

				ImageWriter iw = it.next();
				ImageWriteParam iwp = iw.getDefaultWriteParam();
				iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
				iwp.setCompressionQuality(compressRatio);
				iw.setOutput(fileImageOutputStream);
				iw.write(null, new IIOImage((BufferedImage) itemp, null, null), iwp);
				iw.dispose();
				fileImageOutputStream.flush();
				fileImageOutputStream.close();
				File f = new File(fileWholePath);
				cutImg(f, fileWholePath);
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	static void cutImg(File f, String fileWholePath) throws IOException {
		FileInputStream is = null;
		ImageInputStream iis = null;

		try {
			// 读取图片文件
			is = new FileInputStream(f);
			Iterator<ImageReader> it = ImageIO.getImageReadersByFormatName("jpg");
			ImageReader reader = it.next();
			// 获取图片流
			iis = ImageIO.createImageInputStream(is);
			reader.setInput(iis, true);

			ImageReadParam param = reader.getDefaultReadParam();

			/**
			 * 图片裁剪区域。Rectangle 指定了坐标空间中的一个区域，通过 Rectangle 对象 的左上顶点的坐标（x，y）、宽度和高度可以定义这个区域。
			 */
			Rectangle rect = new Rectangle(27, 0, 170, rsHeight);

			// 提供一个 BufferedImage，将其用作解码像素数据的目标。
			param.setSourceRegion(rect);
			BufferedImage bi = reader.read(0, param);

			// 保存新图片
			ImageIO.write(bi, "jpg", new File(fileWholePath));
		} finally {
			if (is != null) {
				is.close();
			}
			if (iis != null) {
				iis.close();
			}
		}
	}

	static void getFile(File f) {
		if (f == null) {
			return;
		}
		if (f.isFile()) {
			list.add(f);
			return;
		}

		if (f.isDirectory()) {
			File[] f1 = f.listFiles();
			for (File f2 : f1) {
				if (f2.isFile()) {
					if (f2.getName().equals(f.getName() + "_m500.jpg")) {
						list.add(f2);
					}
				} else {
					getFile(f2);
				}
			}
		}
	}
}
